package org.easy.socket.client.plugin;

import org.smartboot.socket.StateMachineEnum;
import org.smartboot.socket.extension.plugins.AbstractPlugin;
import org.smartboot.socket.transport.AioQuickClient;
import org.smartboot.socket.transport.AioSession;

import java.nio.channels.AsynchronousChannelGroup;

/**
 * @Description: 重连插件
 * @Author: wxl
 * @CreateTime: 2023/1/16 14:37
 */
public class ReconnectPlugin extends AbstractPlugin<String> {

    private final AsynchronousChannelGroup asynchronousChannelGroup;
    private final AioQuickClient client;
    private boolean shutdown;

    public ReconnectPlugin(AioQuickClient client) {
        this(client, (AsynchronousChannelGroup)null);
    }

    public ReconnectPlugin(AioQuickClient client, AsynchronousChannelGroup asynchronousChannelGroup) {
        this.shutdown = false;
        this.client = client;
        this.asynchronousChannelGroup = asynchronousChannelGroup;
    }

    @Override
    public void stateEvent(StateMachineEnum stateMachineEnum, AioSession session, Throwable throwable) {
        if (stateMachineEnum == StateMachineEnum.SESSION_CLOSED && !this.shutdown) {
            try {
                if (this.asynchronousChannelGroup == null) {
                    this.client.start();
                } else {
                    this.client.start(this.asynchronousChannelGroup);
                }
            } catch (Exception var5) {
                this.shutdown = true;
                var5.printStackTrace();
            }

        }
    }

    public void shutdown() {
        this.shutdown = true;
    }

}
